package com.jww.cloud.auth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jww.base.am.common.AmConstants;
import com.jww.base.am.model.dos.SysResourceDO;
import com.jww.cloud.auth.service.PermissionService;
import com.jww.cloud.service.user.client.ResourceProviderClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 权限服务实现类
 *
 * @author wanyong
 * @date 2019-1-14 15:23
 */
@Slf4j
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private ResourceProviderClient resourceProviderClient;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        boolean hasPermission = false;
        Object principal = authentication.getPrincipal();
        if (!ObjectUtils.isEmpty(principal)) {
            if (AmConstants.USERNAME_ADMIN.equals(principal)) {
                return true;
            }
            List<SysResourceDO> sysResourceDOList = resourceProviderClient.listByUsername(principal.toString());
            for (SysResourceDO sysResourceDO : sysResourceDOList) {
                if (StringUtils.isNotEmpty(sysResourceDO.getRequestUrl())
                        && antPathMatcher.match(sysResourceDO.getRequestUrl(), request.getRequestURI())
                        && request.getMethod().equalsIgnoreCase(sysResourceDO.getMethod())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
